package com.hqbzl.chat.handler;

import static java.util.stream.Collectors.toSet;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

import com.hqbzl.chat.factory.Factory;
import com.hqbzl.chat.model.GCreageMessage;
import com.hqbzl.chat.model.Group;

import com.hqbzl.chat.model.ResponseMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@Sharable
public final class GroupCreateMessageHandler extends SimpleChannelInboundHandler<GCreageMessage> {

    // 创建群
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GCreageMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        String members = msg.getMembers();
        Set<String> users = Arrays.stream(members.split(",")).filter(x -> x.length() > 1).collect(toSet());
        final Group group = Factory.groupSession.query(groupName);
        if (group == null) {
            Factory.groupSession.createGroup(groupName, users);
            Group joinGroup = Factory.groupSession.query(groupName);
            final List<Channel> memberChannel = Factory.groupSession.getMemberChannel(groupName);
            for (Channel channel : memberChannel) {
                final ResponseMessage build = ResponseMessage.builder().result(true).msg("已经已经被拉入群 " + groupName).build();
                channel.writeAndFlush(build);
            }
        } else {
            final ResponseMessage build = ResponseMessage.builder().result(false).msg("群已存在仓库失败").build();
            ctx.writeAndFlush(build);
        }


    }
}